<template>
  <div class="app-management-container">
    <!-- 左侧折叠面板 -->
    <div class="left-panel" :class="{ collapsed: isCollapsed }" v-if="AppConfig && AppConfig.KnowledgeQa">
      <el-collapse v-model="activeCollapseItems" class="config-collapse">
        <el-collapse-item title="模型配置" name="model">
          <template #title>
            <div class="collapse-header">
              <el-icon><Cpu /></el-icon>
              <span>模型配置</span>
            </div>
          </template>
          <div class="collapse-content">
            <el-form label-position="top" class="elegant-form">
              <el-form-item label="思考模型">
                <el-select
                  v-model="AppConfig.KnowledgeQa.ThoughtModel.Name"
                  placeholder="请选择思考模型"
                  class="model-select"
                >
                  <el-option :label="AppConfig.KnowledgeQa.ThoughtModel.AliasName" :value="AppConfig.KnowledgeQa.ThoughtModel.Name" />
                </el-select>
              </el-form-item>

              <el-form-item label="生成模型">
                <el-select
                  v-model="AppConfig.KnowledgeQa.Model.Name"
                  placeholder="请选择生成模型"
                  class="model-select"
                >
                  <el-option v-for="(value,key) in modelList" :key="key" :label="value.AliasName" :value="value.ModelName" />
                </el-select>
              </el-form-item>

              <el-form-item label="上下文改写">
                <div class="elegant-switch">
                  <el-switch
                    v-model="AppConfig.KnowledgeQa.Model.IsUseContext"
                  />
                  <div class="switch-description">
                    大模型将结合历史回答，补全当前问题
                  </div>
                </div>
              </el-form-item>

              <el-form-item label="上下文记忆轮数">
                <div class="elegant-input">
                  <el-input-number v-model="AppConfig.KnowledgeQa.Model.HistoryLimit" :min="1" :max="1000" />
                  <el-tooltip
                    effect="light"
                    placement="top"
                    content="轮数越多，多轮对话的关联越高，但消耗的token也会越多"
                  >
                    <el-icon class="tooltip-icon"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-item>

        <el-collapse-item title="角色指令" name="role">
          <template #title>
            <div class="collapse-header">
              <el-icon><User /></el-icon>
              <span>角色指令</span>
            </div>
          </template>
          <div class="collapse-content">
            <el-input
              v-model="AppConfig.KnowledgeQa.RoleDescription"
              type="textarea"
              :rows="10"
              placeholder="请输入角色指令"
              resize="none"
              class="elegant-textarea"
            />
          </div>
        </el-collapse-item>

        <el-collapse-item title="欢迎语" name="welcome">
          <template #title>
            <div class="collapse-header">
              <el-icon><ChatDotRound /></el-icon>
              <span>欢迎语</span>
            </div>
          </template>
          <div class="collapse-content">
            <el-input
              v-model="AppConfig.KnowledgeQa.Greeting"
              type="textarea"
              :rows="3"
              placeholder="请输入欢迎语"
              resize="none"
              class="elegant-textarea"
            />
          </div>
        </el-collapse-item>

        <el-collapse-item title="知识库" name="knowledge">
          <template #title>
            <div class="collapse-header">
              <el-icon><Collection /></el-icon>
              <span>知识库</span>
            </div>
          </template>
          <div class="collapse-content">
            <div class="elegant-switch">
              <el-switch
                v-model="zskDoc"
                active-text="启用文档"
                inactive-text=""
              />
            </div>
            <div class="elegant-switch">
              <el-switch
                v-model="zskQa"
                active-text="启用问答"
                inactive-text=""
              />
            </div>
          </div>
        </el-collapse-item>

        <el-collapse-item title="联网搜索" name="search">
          <template #title>
            <div class="collapse-header">
              <el-icon><Search /></el-icon>
              <span>联网搜索</span>
            </div>
          </template>
          <div class="collapse-content">
            <div class="elegant-switch">
              <el-switch
                v-model="zskSearch"
                active-text="启用联网搜索"
                inactive-text=""
              />
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>

    <!-- 右侧iframe区域 -->
    <div v-if="iframeUrl" class="right-iframe" :class="{ 'full-width': isCollapsed }">
      <iframe
        :src="iframeUrl"
        frameborder="0"
        class="chat-iframe"
        id="chatIframeContainer"
        ref="iframeRef"
      ></iframe>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted,computed } from "vue";
import { useRoute } from 'vue-router'
import { describeApp,listModel,modifyApp,createRelease,describeRelease } from "@/api/modules/auth";
import { onBeforeRouteLeave } from 'vue-router'
import { ElMessage, ElLoading } from "element-plus";
import bus from '@/bus/index.js'
const route = useRoute()
const appData = ref(null)
const loading = ref(false)
// 页面配置
const AppConfig = ref({});
// 模型列表
const modelList = ref([]);
// 获取应用ID
const appId = computed(() => route.params.id)
// 
const iframeUrl = ref("");
const zskDoc = computed({
  get() {
    let status = false;
    if(AppConfig.value && AppConfig.value.KnowledgeQa){
      const arr = AppConfig.value.KnowledgeQa.Search;
      if(arr && arr.length > 0){
        const data = arr.filter((item)=>{
          if(item.Type == 'doc'){
            return item
          }
        })  
        status = data[0].IsEnabled;
      }else{
        status = false
      }
    }else{
      status = false
    }
    return status;
  },
  set (newValue) {
    if(AppConfig.value && AppConfig.value.KnowledgeQa){
      const arr = AppConfig.value.KnowledgeQa.Search;
      if(arr && arr.length > 0){
        arr.forEach(item => {
          if(item.Type == 'doc'){
            item.IsEnabled = newValue
          }
        })
      }
    }
  }
})
const zskQa = computed({
  get() {
    let status = false;
    if(AppConfig.value && AppConfig.value.KnowledgeQa){
      const arr = AppConfig.value.KnowledgeQa.Search;
      if(arr && arr.length > 0){
        const data = arr.filter((item)=>{
          if(item.Type == 'qa'){
            return item
          }
        })  
        status = data[0].IsEnabled;
      }else{
        status = false
      }
    }else{
      status = false
    }
    return status;
  },
  set (newValue) {
    if(AppConfig.value && AppConfig.value.KnowledgeQa){
      const arr = AppConfig.value.KnowledgeQa.Search;
      if(arr && arr.length > 0){
        arr.forEach(item => {
          if(item.Type == 'qa'){
            item.IsEnabled = newValue
          }
        })
      }
    }
  }
})

const zskSearch = computed({
  get() {
    let status = false;
    if(AppConfig.value && AppConfig.value.KnowledgeQa){
      const arr = AppConfig.value.KnowledgeQa.Search;
      if(arr && arr.length > 0){
        const data = arr.filter((item)=>{
          if(item.Type == "search"){
            return item
          }
        })  
        status = data[0].IsEnabled;
      }else{
        status = false
      }
    }else{
      status = false
    }
    return status;
  },
  set (newValue) {
    if(AppConfig.value && AppConfig.value.KnowledgeQa){
      const arr = AppConfig.value.KnowledgeQa.Search;
      if(arr && arr.length > 0){
        arr.forEach(item => {
          if(item.Type == "search"){
            item.IsEnabled = newValue
          }
        })
      }
    }
  }
})
// 获取应用详情数据
const fetchAppData = async () => {
  try {
    loading.value = true
    const res = await describeApp(appId.value)
    appData.value = res.data
    console.log(appData.value,'appData.value')
    iframeUrl.value = 'http://localhost:9091/#/chat?AppBizId='+appData.value.AppBizId
    AppConfig.value = appData.value.AppConfig
  } catch (error) {
    console.error('获取应用详情失败:', error)
    ElMessage.error('获取应用详情失败')
  } finally {
    loading.value = false
  }
}

const fetchListModel = async () => {
  const res = await listModel();
  modelList.value = res.data.List;
}

// 左侧面板状态
const isCollapsed = ref(false);
const activeCollapseItems = ref(["model", "role", "welcome","knowledge","search"]);
const knowledgeBaseEnabled = ref(true);
const webSearchEnabled = ref(false);


const outputConfig = ref({
  format: "markdown",
});

const advancedConfig = ref({
  temperature: 0.7,
});

// iframe引用
const iframeRef = ref(null);

// 方法
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};

onBeforeRouteLeave(async (to, from) => {
  if(appData.value && appData.value.AppConfig){
    const res = await modifyApp(appData.value.AppBizId,appData.value.BaseConfig,appData.value.AppConfig)
  }
})
let setIntervalTimer = null;
// 初始化时设置iframe高度
onMounted(async () => {
  if (appId.value) {
    await fetchListModel();
    await fetchAppData();
  }
  bus.on("faBuZsMx",async ()=>{
    const loading = ElLoading.service({
      lock: true,
      text: "应用发布中...",
      background: "rgba(0, 0, 0, 0.7)",
    });
    // modifyApp()
    if(appData.value && appData.value.AppConfig){
      const res = await modifyApp(appData.value.AppBizId,appData.value.BaseConfig,appData.value.AppConfig)
      
      if(res.status == '200'){
        const res = await createRelease(appData.value.AppBizId);
        setIntervalTimer = setInterval(async ()=>{
          const res = await describeRelease(appData.value.AppBizId);
          if(res.data.Status == 3 || res.data.Status == 7 || res.data.Status == 9){
            clearInterval(setIntervalTimer);
            if(res.data.Status == 3){
              ElMessage.success(res.data.StatusDesc);
            }else{
              ElMessage.error(res.data.StatusDesc);
            }
            loading.close();
          } 
          // console.log(res.data.StatusDesc,res.data.Status,'modifyApp.value')
        },3000)
      }
    }
  })
});
</script>

<style scoped lang="scss">
.app-management-container {
  display: flex;
  height: calc(100vh - 88px);
  overflow: hidden;
  background: #f8fafc;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
}

.left-panel {
  width: 500px;
  height: 100%;
  background: #ffffff;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.05);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  flex-direction: column;
  position: relative;
  z-index: 1;
  
  &.collapsed {
    transform: translateX(-100%);
    opacity: 0;
    width: 0;
  }
}

.config-collapse {
  flex: 1;
  overflow-y: auto;
  // padding: 16px;
  background: transparent;
  
  :deep(.el-collapse-item__header) {
    height: 56px;
    line-height: 56px;
    padding: 0 20px;
    font-size: 15px;
    font-weight: 500;
    color: #1a1a1a;
    border-bottom: none;
    background: transparent;
    transition: all 0.2s ease;
    
    &:hover {
      background: rgba(0, 0, 0, 0.02);
    }
  }
  
  :deep(.el-collapse-item__content) {
    padding: 0 20px 20px;
    background: transparent;
  }
}

.collapse-header {
  display: flex;
  align-items: center;
  gap: 10px;
  
  .el-icon {
    font-size: 18px;
    color: #5e6c84;
  }
  
  span {
    font-weight: 500;
  }
}

.collapse-content {
  padding: 16px 0;
}

.elegant-form {
  .el-form-item {
    margin-bottom: 24px;
    
    :deep(.el-form-item__label) {
      padding-bottom: 8px;
      font-size: 13px;
      color: #5e6c84;
      font-weight: 500;
    }
  }
}

.model-select {
  width: 100%;
}

.elegant-switch {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  
  :deep(.el-switch__label) {
    color: #5e6c84;
    font-size: 13px;
    font-weight: 500;
    
    &.is-active {
      color: #1a1a1a;
    }
  }
  
  .switch-description {
    font-size: 12px;
    color: #8993a4;
    line-height: 1.5;
    margin-top: 4px;
  }
}

.elegant-input {
  display: flex;
  align-items: center;
  gap: 10px;
  
  :deep(.el-input-number) {
    width: 120px;
  }
  
  .tooltip-icon {
    color: #8993a4;
    cursor: pointer;
    transition: all 0.2s ease;
    
    &:hover {
      color: #4c9aff;
    }
  }
}

.elegant-textarea {
  :deep(.el-textarea__inner) {
    min-height: 120px;
    border-radius: 6px;
    border: 1px solid #dfe1e6;
    padding: 12px;
    font-size: 14px;
    line-height: 1.5;
    transition: all 0.2s ease;
    
    &:hover {
      border-color: #c1c7d0;
    }
    
    &:focus {
      border-color: #4c9aff;
      box-shadow: 0 0 0 2px rgba(76, 154, 255, 0.2);
    }
  }
}

.right-iframe {
  flex: 1;
  height: 100%;
  background: #ffffff;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  
  &.full-width {
    margin-left: 0;
  }
}

.chat-iframe {
  width: 100%;
  height: 100% !important;
  border: none;
  background: transparent;
}

</style>